#!/bin/bash
#

WORK_DIR="$(dirname $0)/../"
#UWSGI_BIN=venv/bin/uwsgi
# UWSGI_PIDFILE=venv/run.pid
UWSGI_BIN=/usr/local/bin/uwsgi
UWSGI_PIDFILE=/tmp/uwsgi.pid
UWSGI_CONF=tools/uwsgi.ini

PID=$(cat ${WORK_DIR}/${UWSGI_PIDFILE} 2> /dev/null)

cd ${WORK_DIR}

result_echo() {
   if [ $1 == 0 ]; then
       echo -e "\033[32mSuccess\033[0m"
   else
       echo -e "\033[31mFailed\033[0m"
   fi
}

start_server() {
   if [ "$PID" != "" ] &&  ps -c ${PID} &> /dev/null; then
       echo "Server already running (pid: $PID) ..."
   else
       echo -n "Starting server ...                "
       ${UWSGI_BIN} ${UWSGI_CONF} &> /dev/null
       result_echo $?
   fi
}

stop_server() {
   if [ "$PID" = "" ] || ! ps -c ${PID} &> /dev/null; then
       echo "Server already stopped"
   else
       echo -n "Stopping server ...                "
       ${UWSGI_BIN} --stop ${UWSGI_PIDFILE} &> /dev/null
       result_echo $?
   fi
}

reload_server() {
   if [ "$PID" = "" ] || ! ps -c $PID &> /dev/null; then
       start_server
   else
       echo -n "Reloading server ...               "
       ${UWSGI_BIN} --reload ${UWSGI_PIDFILE} &> /dev/null
       result_echo $?
   fi
}

clean_server() {
    echo -n "Clean server ...                   "
    rm -f ~/.subversion/auth/svn.simple/*
    find . -path ./venv -prune -o -type f -name '*.py' -print |xargs rm -f
    result_echo $?
}

case "$1" in
    start)
        start_server
        ;;
    stop)
        stop_server
        ;;
    restart)
        stop_server
        sleep 2
        start_server
        ;;
    reload)
        reload_server
        ;;
    clean)
        clean_server
        ;;
    *)
        echo "Usage: $0 start|stop|restart|reload|clean"
        ;;
esac